using System;
using System.Xml;
using System.Data;

namespace OR.Reuse.Persistence
{
	/// <summary>
    /// Summary description for ModelElementBase.
	/// </summary>
	public abstract class ModelElementBase<PKTYPE, MANAGER>
	{
        private PKTYPE mId;
        private MANAGER mDataManager;

        public PKTYPE Id
        {
            get { return mId; }
            set { mId = value; }
        }

        public MANAGER DataManager
        {
            get { return (mDataManager); }
            set { mDataManager = value; }
        }

        public bool IsNew
        {
            get { return GetIsNew(); }
        }

        public ModelElementBase(MANAGER dataManager)
        {
            if (dataManager == null)
            {
                throw new ArgumentNullException("dataManager");
            }

            this.DataManager = dataManager;
        }

        private bool GetIsNew()
        {
            bool rtnVal = false;

            if ((typeof(PKTYPE) == typeof(Int32)) || (Convert.ToInt32(this.Id) == 0))
            {
                rtnVal = true;
            }
            else
            {
                throw new NotSupportedException();
            }

            return rtnVal;
        }

        public void Load(PKTYPE existingId)
        {
            this.Id = existingId;

            this.Refresh();
        }

        public void Save()
        {
            if (this.IsNew)
            {
                this.SaveNew();
            }
            else
            {
                this.SaveExisting();
            }
        }

        /// <summary>
        /// Populates the model element with data from the database matching the current Id.
        /// </summary>
        public abstract void Refresh();

        public abstract void Load(DataRow existingRow);

        protected abstract void SaveNew();

        protected abstract void SaveExisting();
        
        public ModelElementBase()
		{
			//
			// TODO: Add constructor logic here
			//
		}
	}
}
